package homework2.client;

import homework2.common.CommandType;
import homework2.common.Message;
import homework2.utils.Tool;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Scanner;

/**
 * 用户服务业务逻辑类
 *
 * @author jian
 * @date 2024/01/09 00:48
 **/
public class ClientService {
    public static void getOnlineList(Socket socket) throws IOException, ClassNotFoundException {
        Message message = new Message();
        message.setCommandType(CommandType.USER_LIST);
        ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
        oos.writeObject(message); //发送一个Message对象，向服务端要求在线用户列表
    }

    public static void handleCommand(Socket socket){
        Scanner scanner = new Scanner(System.in);
        String input = ""; // 初始化输入变量
        while (!input.equals("break")) { // 当输入不等于分号时循环
            System.out.print("请输入命令：");
            input = scanner.nextLine();
            String[] params = input.split(" ");
            // 获取用户输入
            // 在这里可以对输入进行处理或执行相应的操作
            switch (input.substring(0,4)){
                case "send":
                    if (params.length == 3){
                        if (params[1].equals("@all")){
                            handleSendAll(params[2], socket);
                        }
                        else{
                            handleSendTargetUser(params[1],params[2], socket);
                        }
                    }
                    break;
                case "show":
                    handleReadFile(params[1], socket);
                    break;
            }
        }

    }

    private static void handleReadFile(String filePath, Socket socket){
        Message message = new Message();
        message.setCommandType(CommandType.SHOW);
        message.setContent(filePath);
        try (ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream())) {
            oos.writeObject(message);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private static void handleSendTargetUser(String target, String filePath, Socket socket) {

        if (Tool.fileIsExist(filePath)){
            try {
                ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
                Tool.sendEncryptedFile(target, oos, filePath,CommandType.TARGET);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

    }

    private static void handleSendAll(String filePath, Socket socket) {
        if (Tool.fileIsExist(filePath)){
            try {
                ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
                Tool.sendEncryptedFile("all", oos, filePath,CommandType.ALL);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }
}


